import request from '@/utils/request'
import OSS from 'ali-oss'

// 获取阿里OSStoken信息
export function aliOssToken(param) {
  return request({
    url: 'spiritik/get_oss_token',
    method: 'post',
    data: param
  })
}

// 阿里oss初始化（美国 us-west-1）
export async function aliClientInit(param) {
  const re = await aliOssToken({
    rid: 1,
    versioncode: 1
  })
  console.log('OSS token返回：', re)

  const aliClient = new OSS({
    region: 'oss-us-west-1',          // ✅ 区域改成美国西部 1
    accessKeyId: re.data.accessKeyId,
    accessKeySecret: re.data.access_key_secret,
    stsToken: re.data.security_token,
    bucket: 'tonespac-media-us'       // ✅ bucket 改成新的
  })

  return aliClient
}

// OSS 文件路径名
export function ossFilePath(filename, keep_origin_name) {
  const mnow = new Date()
  const year = mnow.getFullYear()
  let month = mnow.getMonth() + 1
  if (month < 10) month = '0' + month

  const date_str = `${year}${month}`
  const env_str = process.env.NODE_ENV || 'dev'

  const rootDir = 'source'   // ✅ 统一前缀

  // 随机命名
  let random_name
  if (!keep_origin_name) {
    const extension = filename.includes('.') ? filename.split('.').pop() : ''
    random_name = `${rootDir}/${env_str}/${date_str}/${random_string(6)}_${Date.now()}${extension ? '.' + extension : ''}`
  } else {
    const dotIndex = filename.lastIndexOf('.')
    const baseName = dotIndex !== -1 ? filename.substring(0, dotIndex) : filename
    const extension = dotIndex !== -1 ? filename.substring(dotIndex) : ''
    random_name = `${rootDir}/${env_str}/${date_str}/${baseName}_${random_string(4)}${extension}`
  }
  return random_name
}

function random_string(len) {
  len = len || 32
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz12345678'
  const maxPos = chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}